<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.graduateId"
        placeholder="毕业生ID"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-input
        v-model="listQuery.requirementId"
        placeholder="毕业要求ID"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-input
        v-model="listQuery.evaluationYear"
        placeholder="评价年份"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list || []"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template #default="{ row }">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column label="毕业生ID">
        <template #default="{ row }">
          {{ row.graduateId }}
        </template>
      </el-table-column>
      <el-table-column label="毕业要求ID">
        <template #default="{ row }">
          {{ row.requirementId }}
        </template>
      </el-table-column>
      <el-table-column label="直接评价">
        <template #default="{ row }">
          {{ row.directEvaluation }}
        </template>
      </el-table-column>
      <el-table-column label="自评">
        <template #default="{ row }">
          {{ row.selfEvaluation }}
        </template>
      </el-table-column>
      <el-table-column label="实习评价">
        <template #default="{ row }">
          {{ row.internshipEvaluation }}
        </template>
      </el-table-column>
      <el-table-column label="教师评价">
        <template #default="{ row }">
          {{ row.teacherEvaluation }}
        </template>
      </el-table-column>
      <el-table-column label="综合评分">
        <template #default="{ row }">
          {{ row.comprehensiveScore }}
        </template>
      </el-table-column>
      <el-table-column label="是否达成">
        <template #default="{ row }">
          <el-tag :type="row.isAchieved ? 'success' : 'danger'">
            {{ row.isAchieved ? '达成' : '未达成' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="评价年份">
        <template #default="{ row }">
          {{ row.evaluationYear }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="listQuery.pageNum"
        v-model:page-size="listQuery.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="dialogFormVisible"
      :title="textMap[dialogStatus]"
      width="500px"
    >
      <el-form
        ref="dataFormRef"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="毕业生ID" prop="graduateId">
          <el-input v-model="temp.graduateId" />
        </el-form-item>
        <el-form-item label="毕业要求ID" prop="requirementId">
          <el-input v-model.number="temp.requirementId" />
        </el-form-item>
        <el-form-item label="直接评价" prop="directEvaluation">
          <el-input-number v-model="temp.directEvaluation" :precision="4" :step="0.1" :max="1" :min="0" />
        </el-form-item>
        <el-form-item label="自评" prop="selfEvaluation">
          <el-input-number v-model="temp.selfEvaluation" :precision="4" :step="0.1" :max="1" :min="0" />
        </el-form-item>
        <el-form-item label="实习评价" prop="internshipEvaluation">
          <el-input-number v-model="temp.internshipEvaluation" :precision="4" :step="0.1" :max="1" :min="0" />
        </el-form-item>
        <el-form-item label="教师评价" prop="teacherEvaluation">
          <el-input-number v-model="temp.teacherEvaluation" :precision="4" :step="0.1" :max="1" :min="0" />
        </el-form-item>
        <el-form-item label="评价年份" prop="evaluationYear">
          <el-input-number v-model="temp.evaluationYear" :min="2000" :max="2100" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getGraduateRequirementAchievementList, getGraduateRequirementAchievement, addGraduateRequirementAchievement, updateGraduateRequirementAchievement, deleteGraduateRequirementAchievement } from '@/api/graduateRequirementAchievement'

const dataFormRef = ref(null)
const list = ref(null)
const total = ref(0)
const listLoading = ref(true)
const listQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  graduateId: undefined,
  requirementId: undefined,
  evaluationYear: undefined
})
const temp = reactive({
  id: undefined,
  graduateId: '',
  requirementId: undefined,
  directEvaluation: 0,
  selfEvaluation: 0,
  internshipEvaluation: 0,
  teacherEvaluation: 0,
  evaluationYear: new Date().getFullYear()
})
const dialogFormVisible = ref(false)
const dialogStatus = ref('')
const textMap = {
  update: '编辑',
  create: '添加'
}
const rules = {
  graduateId: [{ required: true, message: '请输入毕业生ID', trigger: 'blur' }],
  requirementId: [{ required: true, message: '请输入毕业要求ID', trigger: 'blur' }],
  directEvaluation: [{ required: true, message: '请输入直接评价', trigger: 'blur' }],
  selfEvaluation: [{ required: true, message: '请输入自评', trigger: 'blur' }],
  evaluationYear: [{ required: true, message: '请输入评价年份', trigger: 'blur' }]
}

const resetTemp = () => {
  Object.assign(temp, {
    id: undefined,
    graduateId: '',
    requirementId: undefined,
    directEvaluation: 0,
    selfEvaluation: 0,
    internshipEvaluation: 0,
    teacherEvaluation: 0,
    evaluationYear: new Date().getFullYear()
  })
}

const handleCreate = () => {
  resetTemp()
  dialogStatus.value = 'create'
  dialogFormVisible.value = true
  nextTick(() => {
    if (dataFormRef.value) {
      dataFormRef.value.clearValidate()
    }
  })
}

const createData = async () => {
  if (!dataFormRef.value) return
  
  try {
    await dataFormRef.value.validate()
    const response = await addGraduateRequirementAchievement(temp)
    if (response.code === 200) {
      ElMessage.success('创建成功')
      dialogFormVisible.value = false
      getList()
    } else {
      ElMessage.error(response.msg || '创建失败')
    }
  } catch (error) {
    console.error('创建失败:', error)
    ElMessage.error('创建失败')
  }
}

const handleUpdate = (row) => {
  Object.assign(temp, row)
  dialogStatus.value = 'update'
  dialogFormVisible.value = true
  nextTick(() => {
    if (dataFormRef.value) {
      dataFormRef.value.clearValidate()
    }
  })
}

const updateData = async () => {
  if (!dataFormRef.value) return
  
  try {
    await dataFormRef.value.validate()
    const response = await updateGraduateRequirementAchievement(temp)
    if (response.code === 200) {
      ElMessage.success('更新成功')
      dialogFormVisible.value = false
      getList()
    } else {
      ElMessage.error(response.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败')
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认要删除该记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const response = await deleteGraduateRequirementAchievement(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      getList()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleFilter = () => {
  listQuery.pageNum = 1
  getList()
}

const handleSizeChange = (val) => {
  listQuery.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  listQuery.pageNum = val
  getList()
}

const getList = async () => {
  try {
    listLoading.value = true
    const response = await getGraduateRequirementAchievementList(listQuery)
    if (response.code === 200) {
      list.value = response.data.records
      total.value = response.data.total
    } else {
      ElMessage.error(response.msg || '获取列表失败')
    }
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    listLoading.value = false
  }

}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
  margin-right: 10px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
